package com.ruoyi.system.websocket.socket;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.TbCompanyMerchantChatRecord;
import com.ruoyi.system.mapper.TbCompanyMerchantChatRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ServerEndpoint(value = "/websocket/{userAcc}")
@Component
public class WebSocketService {
//    @Autowired
//    private TbCompanyMerchantChatRecordMapper chatRecordMapper;

    @Autowired
    private RedisTemplate<String, String> redis;

    public static RedisTemplate<String, String> redisTemplate;

    @PostConstruct
    public void getRedisTemplate() {
        redisTemplate = this.redis;
    }

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
     */
    private static ConcurrentHashMap<String, WebSocketClient> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 账号信息
     */
    private String userAcc = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userAcc") String userAcc) {

        if (!webSocketMap.containsKey(userAcc)) {
            // 在线数 +1
            addOnlineCount();
        }
        this.session = session;
        this.userAcc = userAcc;
        WebSocketClient client = new WebSocketClient();
        client.setSession(session);
        client.setUri(session.getRequestURI().toString());
        webSocketMap.put(userAcc, client);

        log.info("----------------------------------------------------------------------------");
        log.info("用户连接:" + userAcc + ",当前在线人数为:" + getOnlineCount());
        Map<String, String> map = new HashMap<>();
        try {
            map.put("fromUser", "server");
            map.put("msg", "连接成功");
            sendMessage(JSON.toJSONString(map));
        } catch (IOException e) {
            log.error("用户:" + userAcc + ",网络异常!");
        }

        //回显消息
        reSendMessage(userAcc);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //消息保存到数据库


        //移除用户
        if (webSocketMap.containsKey(userAcc)) {
            webSocketMap.remove(userAcc);
            // 在线数 -1
            subOnlineCount();
        }
        log.info("----------------------------------------------------------------------------");
        log.info(userAcc + "用户退出,当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到用户消息:" + userAcc + ",报文:" + message);

        Map<String, String> map = JSON.parseObject(message, Map.class);
        //发送给自己
        sendMessage(map.get("fromUser"), message);
        //对方在线就发送给对方
        if (webSocketMap.containsKey(map.get("toUser"))) {
            sendMessage(map.get("toUser"), message);
        }
        //消息保存到redis
        saveMessageToRedis(message);
    }

    //消息回显
    public void reSendMessage(String userAcc) {
        Long size = redisTemplate.opsForList().size("merchant_company_msgKey");
        if (size > 0) {
            Map<String, String> msgMap;
            List<String> messages = redisTemplate.opsForList().range("merchant_company_msgKey", 0, -1);
            // 打印List中的所有消息
            for (String msg : messages) {
                msgMap = JSON.parseObject(msg, Map.class);
                //发送人登录，则回显给发送人
                if (msgMap.get("fromUser").equals(userAcc)) {
                    sendMessage(msgMap.get("fromUser"), msg);
                }
                //接收人登录，则回显给接收人
                if (msgMap.get("toUser").equals(userAcc)) {
                    sendMessage(msgMap.get("toUser"), msg);
                }
            }
        }
    }

    //消息保存到redis
    public void saveMessageToRedis(String message) {
        //消息保存到数据库、redis
        if (StringUtils.isNotBlank(message)) {
            String key = "merchant_company_msgKey";
            String value = message;
            // 将消息添加到List的末尾
            redisTemplate.opsForList().rightPush(key, value);
        }
    }

    //消息保存到数据库
    public void saveMessageToDb() throws Exception {
        Long size = redisTemplate.opsForList().size("merchant_company_msgKey");

        if (size > 0) {
            Map<String, String> msgMap;
//            TbCompanyMerchantChatRecord tbCompanyMerchantChatRecord = new TbCompanyMerchantChatRecord();
            List<String> messages = redisTemplate.opsForList().range("merchant_company_msgKey", 0, -1);
            for (String msg : messages) {
//                msgMap = JSON.parseObject(msg, Map.class);

            }
        }
    }


    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userAcc + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 连接服务器成功后主动推送
     */
    public void sendMessage(String message) throws IOException {
        synchronized (session) {
            this.session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 向指定客户端发送消息
     *
     * @param userAcc
     * @param message
     */
    public static void sendMessage(String userAcc, String message) {
        try {
            WebSocketClient webSocketClient = webSocketMap.get(userAcc);
            if (webSocketClient != null) {
                webSocketClient.getSession().getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketService.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketService.onlineCount--;
    }

    public static void setOnlineCount(int onlineCount) {
        WebSocketService.onlineCount = onlineCount;
    }


    public static ConcurrentHashMap<String, WebSocketClient> getWebSocketMap() {
        return webSocketMap;
    }

    public static void setWebSocketMap(ConcurrentHashMap<String, WebSocketClient> webSocketMap) {
        WebSocketService.webSocketMap = webSocketMap;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getUserAcc() {
        return userAcc;
    }

    public void setUserAcc(String userAcc) {
        this.userAcc = userAcc;
    }
}
